import {pathJoin} from "plain-micro-application";
import {Libs} from "@/micro/utils/Libs";

export const MicroLibService = (() => {

    /**
     * 一些依赖数据
     * @author  韦胜健
     * @date    2021/2/25 17:45
     */
    const data = (() => {
        const state = {
            version: '0.0.1',
            dependency: Libs,
        } as {
            version: string,
            dependency: {
                [k: string]: {
                    defer?: boolean,
                    alwaysChange?: boolean,
                    basePath?: string,
                    js?: string,
                    css?: string,
                    loadOnStart?: string,
                    loadSeq?: number,
                    version?: string,
                } | undefined
            }
        }

        /*立即获取 __webpack_public_path__ 得到的是不对的，没有域名ip以及端口*/
        /*setTimeout(() => {
            console.log(state.dependency)
            console.log('BASE 应用的部署地址', __webpack_public_path__)
        }, 1000)*/

        const get = (libName: string) => {
            const lib = state.dependency[libName]
            if (!lib) {
                throw new Error(`依赖库：${libName} 不存在！`)
            }
            if (!lib.js && !lib.css) {
                console.log(lib)
                throw new Error(`依赖库没有指定js以及css：${libName}`)
            }
            return lib
        }
        return {
            state,
            get,
        }
    })();

    /**
     * 加载js或者css文件
     * @author  韦胜健
     * @date    2021/2/25 17:46
     */
    const request = (() => {
        const cacheMap = {} as Record<string, Promise<any>>
        return (url: string) => {
            url = __webpack_public_path__ + pathJoin(url)
            if (!cacheMap[url]) {
                cacheMap[url] = new Promise<any>((resolve, reject) => {
                    if (/\.js(\?.*)?/.test(url)) {
                        const el = document.createElement('script') as HTMLScriptElement
                        el.setAttribute('src', url)
                        el.onload = resolve
                        el.onerror = reject
                        document.body.appendChild(el)
                    } else if (/\.css(\?.*)?/.test(url)) {
                        const el = document.createElement('link') as HTMLLinkElement
                        el.setAttribute('rel', 'stylesheet')
                        el.setAttribute('type', 'text/css')
                        el.setAttribute('href', url)
                        el.onload = resolve
                        el.onerror = reject
                        document.body.appendChild(el)
                    }
                })
            }
            return cacheMap[url]
        }
    })();

    /**
     * 加载某个依赖
     * @author  韦胜健
     * @date    2021/2/25 17:46
     */
    const load = (() => {
        const Win = window as any
        const _load = async (libName: string): Promise<any> => {
            if (!!Win[libName]) return Win[libName]

            const lib = data.get(libName)
            const ret = [] as Promise<void>[]
            let version = !!lib.version ? `?version=${lib.version}` : ''
            if (!!lib.js) ret.push(request(lib.js + version))
            if (!!lib.css) ret.push(request(lib.css + version))
            await Promise.all(ret)
            return (Win)[libName]
        }
        return Object.assign((libNames: string | string[]) => {
            if (Array.isArray(libNames)) {
                const names = Array.isArray(libNames) ? libNames : [libNames]
                return Promise.all(names.map(_load))
            } else {
                return _load(libNames)
            }
        }, {
            echarts: () => _load('echarts'),
        })
    })();

    return {
        load,
    }
})();
